<template>
  <div>
    <el-form ref="addForm" :model="addNew" :rules="rules" label-width="150px"
             style="width: 1000px;position:relative;overflow: hidden;height: 400px">
      <el-form-item label="类别名" prop="name">
        <el-input v-model="addNew.name"></el-input>
      </el-form-item>
      <el-form-item label="上级类别" prop="parentId">
        <el-cascader :options="categoryTable" :props="{ expandTrigger: 'hover' }" @change="handleChange"/>
      </el-form-item>
      <el-form-item label="序号" prop="sort">
        <el-input v-model="addNew.sort"></el-input>
      </el-form-item>
      <el-form-item style="position: absolute;left: 50%;bottom: 0;transform: translateX(-71%)">
        <el-button type="primary" @click="submitForm('addForm')">添加</el-button>
        <el-button type="danger" @click="resetForm('addForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "categoryAddNew",
  data() {
    return {
      categoryTable: [],
      addNew: {
        name: "",
        parentId: "",
        sort: "",
      },
      rules: {
        name: [],
        parentId: [],
        sort: [],
      }
    }
  },
  methods: {
    handleChange(value) {
      this.addNew.parentId = value[value.length - 1];
    },
    loadCategory() {
      let url = "http://localhost:9999/zx-court/category/treeList";
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        if (response.data.state === 200) {
          this.categoryTable = response.data.data;
        }
      })
    },
    submitForm(addForm) {
      this.$refs[addForm].validate((valid) => {
        if (valid) {
          let url = "http://localhost:9999/zx-court/category/addNew";
          if (this.addNew.parentId === ""){
            this.addNew.parentId = "0";
          }
          let addNewData = this.qs.stringify(this.addNew);
          this.axios.create(
              {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
          ).post(url, addNewData).then((response) => {
            if (response.data.state === 200) {
              this.$message({message: "新增数据完毕，返回并刷新类别列表", type: "success"});
              this.resetForm();
              this.$emit("changeTab", "categoryList");
            } else {
              this.$message({message: response.data.message, type: "error"})
            }
          })
        } else {
          this.$message({message: "有数据不符合规范", type: "error"})
        }
      });
    },
    resetForm() {
      this.$refs.addForm.resetFields();
      this.addNew.isParent = 0;
    },//用于清除el-form内所有内容
  },
  mounted() {
    this.loadCategory();
  }
}
</script>

<style scoped>

</style>